package com.lyl.config;

import com.lyl.service.impl.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

/**
 * @author lylbell
 * @date 2021-06-17 19:07
 */
//授权服务器生成的token，是存在于内存当中，若有多台授权服务器，就会出现token不共享问题。解决办法：将token存于redis中
//授权服务器使用jwt去生成token，资源服务器直接从token中获取用户信息，
@EnableAuthorizationServer //开启授权服务器。
@Configuration
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private PasswordEncoder passwordEncoder;


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailServiceImpl userDetailsService;

    //配置第三方客户端
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("coin-api")//第三方客户端的名称
                .secret(passwordEncoder.encode("coin-secret"))//第三方客户端密钥
                .scopes("all")//第三方客户端授权范围
                .authorizedGrantTypes("password","refresh_token")   //添加一种验证方式refresh_token
                .accessTokenValiditySeconds(24 * 3600) //token的有效期
                .refreshTokenValiditySeconds(7 * 24 * 3600)//refresh-token的有效期
                //用于服务内部，生成临时的token
                .and()
                .withClient("inside-app")
                .secret(passwordEncoder.encode("inside-secret"))
                .secret("all")
                .authorizedGrantTypes("client_credentials")
                .accessTokenValiditySeconds(7 * 24 *3600) ;
        super.configure(clients);
    }


    /**
     * 配置验证管理器和userDetailService
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService) //使用自定义的userDetailServiceImpl
                .tokenStore(jwtTokenStore()) //使用jwt存储token
                .tokenEnhancer(jwtAccessTokenConverter())  //tokenEnhancer:token怎么产生
        ;
        super.configure(endpoints);
    }


    private TokenStore jwtTokenStore() {
        JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter());
        return jwtTokenStore;
    }

    private JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        //加载私钥
        ClassPathResource classPathResource = new ClassPathResource("coinexchange.jks");
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "coinexchange".toCharArray());
        tokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("coinexchange","coinexchange".toCharArray()));//设置一个密钥对
        return tokenConverter;
    }

    //jwt存在问题：登出问题。生成的token无法销毁，只能等token过期。解决：将token存于redis当中，登录即销毁redis中的token
}
